using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
using Debug = UnityEngine.Debug;

namespace XFramework
{
    public static class UnityExtension
    {
        /// <summary>
        /// 设置物体显示隐藏
        /// </summary>
        /// <param name="self"></param>
        /// <param name="isActive"></param>
        public static void SetActive(this Component self, bool isActive)
        {
            self.gameObject?.SetActive(isActive);
        }

        /// <summary>
        /// 获取组件，如果没有，则添加
        /// </summary>
        /// <param name="transform"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOrAddComponent<T>(this Transform transform) where T : Component
        {
            var comp = transform.GetComponent<T>();
            return comp == null ? transform.gameObject.AddComponent<T>() : comp;
        }

        /// <summary>
        /// 跟据名称查找所有子节点中指定的节点
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="name">子节点名称</param>
        /// <param name="active">查找范围是否包括隐藏节点</param>
        /// <returns></returns>
        public static Transform FindInAllChild(this Transform transform, string name, bool active = false)
        {
            var list = transform.GetComponentsInChildren<Transform>(active);
            for (var i = 0; i < list.Length; i++)
            {
                var t = list[i];
                if (t.gameObject.name == name)
                {
                    return t;
                }
            }

            return null;
        }

        /// <summary>
        /// 删除所有子节点
        /// </summary>
        /// <param name="transform"></param>
        public static void ClearChild(this Transform transform)
        {
            for (var i = 0; i < transform.childCount; i++)
            {
                var go = transform.GetChild(i).gameObject;
                GameObject.Destroy(go);
            }
        }

        /// <summary>
        /// 寻找父节点中的组件
        /// </summary>
        /// <param name="transform"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T FindComponentInParents<T>(this Transform transform) where T : Component
        {
            var component = transform.GetComponent<T>();
            if (component != null)
            {
                return component;
            }

            return transform.parent != null ? FindComponentInParents<T>(transform.parent) : null;
        }

        /// <summary>
        /// 移除物体上挂载的脚本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="gameObject"></param>
        public static void RemoveComponent<T>(this GameObject gameObject) where T : MonoBehaviour
        {
            bool existsComponent = gameObject.TryGetComponent(typeof(T), out var component);
            if (existsComponent)
                GameObject.Destroy(component);
        }

        /// <summary>
        /// 重置Transform局部位置旋转缩放
        /// </summary>
        /// <param name="transform"></param>
        public static Transform ResetLocal(this Transform transform)
        {
            transform.localPosition = Vector3.zero;
            transform.localRotation = Quaternion.identity;
            transform.localScale = Vector3.one;
            return transform;
        }

        /// <summary>
        /// 设置绝对位置的x坐标
        /// </summary>
        /// <param name="transform"><see cref="Transform" />对象</param>
        /// <param name="newValue">x 坐标值</param>
        public static Transform SetPositionX(this Transform transform, float newValue)
        {
            Vector3 originalPos = transform.position;
            originalPos.x = newValue;
            transform.position = originalPos;
            return transform;
        }

        /// <summary>
        /// 设置绝对位置的y坐标
        /// </summary>
        /// <param name="transform"><see cref="Transform" />对象</param>
        /// <param name="newValue">y 坐标值</param>
        public static Transform SetPositionY(this Transform transform, float newValue)
        {
            Vector3 originalPos = transform.position;
            originalPos.y = newValue;
            transform.position = originalPos;
            return transform;
        }

        /// <summary>
        /// 设置绝对位置的z坐标
        /// </summary>
        /// <param name="transform"><see cref="Transform" />对象</param>
        /// <param name="newValue">z 坐标值</param>
        public static Transform SetPositionZ(this Transform transform, float newValue)
        {
            Vector3 originalPos = transform.position;
            originalPos.z = newValue;
            transform.position = originalPos;
            return transform;
        }

        /// <summary>
        /// 设置绝对旋转x轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Transform SetEulerAnglesX(this Transform transform, float x)
        {
            transform.eulerAngles = new Vector3(x, transform.eulerAngles.y, transform.eulerAngles.z);
            return transform;
        }

        /// <summary>
        /// 设置绝对旋转y轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static Transform SetEulerAnglesY(this Transform transform, float y)
        {
            transform.eulerAngles = new Vector3(transform.eulerAngles.x, y, transform.eulerAngles.z);
            return transform;
        }

        /// <summary>
        /// 设置绝对旋转z轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        public static Transform SetEulerAnglesZ(this Transform transform, float z)
        {
            transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, z);
            return transform;
        }

        /// <summary>
        /// 设置局部缩放x轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="x"></param>
        public static Transform SetLocalScaleX(this Transform transform, float x)
        {
            transform.localScale = new Vector3(x, transform.localScale.y, transform.localScale.z);
            return transform;
        }

        /// <summary>
        /// 设置局部缩放y轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static Transform SetLocalScaleY(this Transform transform, float y)
        {
            transform.localScale = new Vector3(transform.localScale.x, y, transform.localScale.z);
            return transform;
        }

        /// <summary>
        /// 设置局部缩放z轴
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        public static Transform SetLocalScaleZ(this Transform transform, float z)
        {
            transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, z);
            return transform;
        }

        /// <summary>
        /// 设置世界缩放
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="globalScale">局部缩放</param>
        public static Transform SetGlobalScale(this Transform transform, Vector3 globalScale)
        {
            transform.localScale = Vector3.one;
            Vector3 lossyScale = transform.lossyScale;
            transform.localScale = new Vector3(globalScale.x / lossyScale.x, globalScale.y / lossyScale.y,
                globalScale.z / lossyScale.z);
            return transform;
        }

        /// <summary>
        /// 设置RectTransform宽度
        /// </summary>
        /// <param name="self"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        public static RectTransform SetWidthWithCurrentAnchors(this RectTransform self, float width)
        {
            self.sizeDelta = new Vector2(width, self.sizeDelta.y);
            return self;
        }

        /// <summary>
        /// 设置RectTransform高度
        /// </summary>
        /// <param name="self"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static RectTransform SetHeightWithCurrentAnchors(this RectTransform self, float height)
        {
            self.sizeDelta = new Vector2(self.sizeDelta.x, height);
            return self;
        }
        
        /// <summary>
        /// 检查旋转角度，解决欧拉角旋转万向节锁问题
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static float CheckEuler(this float self)
        {
            if (self > 90 && self < 270)
                return ((self) + 180);
            else if (self > 270 && self < 360)
                return ((self) - 360);
            else
                return self;
        }

    }

    public static class UIExtension
    {
    }

    public static class WindowExtension
    {
        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr intPtr, int nCmdShow);

        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        public static void SetMiniWindow()
        {
            ShowWindow(GetForegroundWindow(), 2);
        }
    }

    public static class PathExtension
    {
        public static string FormatPath(this string self) => self.Replace("\\", "/");

        public static string RemoveSpace(this string self) => self.Replace(" ", "");
    }

    public static class StringExtension
    {
        /// <summary>
        /// string 转 Enum
        /// </summary>
        /// <param name="self"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T ToEnum<T>(this string self)
        {
            return (T)Enum.Parse(typeof(T), self);
        }

        /// <summary>
        /// 字符串是否包含中文
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool ContainsChinese(this string self)
        {
            return Regex.IsMatch(self, @"[\u4e00-\u9fa5]");
        }

        /// <summary>
        /// 字符串是否包含非法字符
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool ContainsUnlawfulness(this string self)
        {
            return Regex.IsMatch(self, @"^\w$");
        }

        /// <summary>
        /// 字符串是否是url链接
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsUrlValid(this string self)
        {
            string regexPattern = @"^(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$";
            return Regex.IsMatch(self, regexPattern);
        }

        /// <summary>
        /// 字符串是否是ip地址
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsIPAddressValid(this string self)
        {
            string regexStrIPV4 =
                (@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");

            return Regex.IsMatch(self, regexStrIPV4) && self != "0.0.0.0";
        }

        /// <summary>
        /// 字符串是否是Email
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsEmailValid(this string self)
        {
            string EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
            return Regex.IsMatch(self, EMAIL_PATTERN);
        }

        /// <summary>
        /// 判断输入的字符串是否只包含数字和英文字母
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsNumAndEnCh(this string input)
        {
            if (input == null || input == string.Empty) return false;
            string pattern = @"^[A-Za-z0-9]+$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }

        /// <summary>
        /// 判断输入的字符串是否是一个超链接
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsURL(this string input)
        {
            if (input == null || input == string.Empty) return false;
            Uri uriResult;
            return Uri.TryCreate(input, UriKind.Absolute, out uriResult)
                   && uriResult != null
                   && !string.IsNullOrEmpty(uriResult.Scheme);
        }

        /// <summary>
        /// 判断是否有特殊字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsSpecialChar(this string str)
        {
            Regex regExp = new Regex("[^0-9a-zA-Z\u4e00-\u9fa5]");
            if (regExp.IsMatch(str))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 是否是用逗号分隔的整型字符串
        /// </summary>
        /// <param name="self"></param>
        /// <returns></returns>
        public static bool IsIntegers(this string self)
        {
            var regex = new Regex(@"\d+(,\d+)*");
            return regex.IsMatch(self);
        }

        /// <summary>
        /// 输入密码判断等级
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string RegexLevel(this string input)
        {
            //复杂 必须有数字与字母和符号混合组成的8-15位数(就是剔除其余格式可能，留下目标格式)
            string rule1 =
                @"^(?![a-zA-Z]{8,15}$)(?![\d{8,15}])(?![!@#$%^&*.]{8,15}$)(?![a-zA-Z\d]{8,15}$)(?![a-zA-Z!@#$%^&*.]{8,15})(?![\d!@#$%^&*.]{8,15}$)
        ([a-zA-Z\d!@#$%^&*.]{8,15}&)";
            //中等  由数字和字母或者数字和符号或者字母和符号组成的8-15位数
            string rule2 =
                @"^(?![a-zA-Z]{8,15}$)(?![\d{8,15}])(?![!@#$%^&*.]{8,15}$)([a-zA-Z\d]|[a-zA-Z!@#$%^&*.]|[\d!@#$%^&*.]){8,15}$";
            //简单  由单一的数字或者字母或者符号组成的8-15位数
            string rule3 = @"^([a-zA-Z]|[\d{8,15}]|[!@#$%^&*.]){8,15}$";
            Regex r1 = new Regex(rule1);
            Regex r2 = new Regex(rule2);
            Regex r3 = new Regex(rule3);
            if (r1.IsMatch(input))
            {
                Debug.Log("密码强度:复杂");
                return "密码强度:复杂";
            }
            else if (r2.IsMatch(input))
            {
                Debug.Log("密码强度：中等");
                return "密码强度：中等";
            }
            else if (r3.IsMatch(input))
            {
                Debug.Log("密码强度：容易");
                return "密码强度：容易";
            }
            else
            {
                Debug.Log("密码输入格式不正确");
                return "密码输入格式不正确";
            }
        }
    }
    
    public static class PositionConvert
    {
        /// <summary>
        /// 世界坐标转换为屏幕坐标
        /// </summary>
        /// <param name="worldPoint">屏幕坐标</param>
        /// <returns></returns>
        public static Vector2 WorldPointToScreenPoint(Vector3 worldPoint)
        {
            // Camera.main 世界摄像机
            Vector2 screenPoint = Camera.main.WorldToScreenPoint(worldPoint);
            return screenPoint;
        }

        /// <summary>
        /// 屏幕坐标转换为世界坐标
        /// </summary>
        /// <param name="screenPoint">屏幕坐标</param>
        /// <param name="planeZ">距离摄像机 Z 平面的距离</param>
        /// <returns></returns>
        public static Vector3 ScreenPointToWorldPoint(Vector2 screenPoint, float planeZ)
        {
            // Camera.main 世界摄像机
            Vector3 position = new Vector3(screenPoint.x, screenPoint.y, planeZ);
            Vector3 worldPoint = Camera.main.ScreenToWorldPoint(position);
            return worldPoint;
        }

        // RectTransformUtility.WorldToScreenPoint
        // RectTransformUtility.ScreenPointToWorldPointInRectangle
        // RectTransformUtility.ScreenPointToLocalPointInRectangle
        // 上面三个坐标转换的方法使用 Camera 的地方
        // 当 Canvas renderMode 为 RenderMode.ScreenSpaceCamera、RenderMode.WorldSpace 时 传递参数 canvas.worldCamera
        // 当 Canvas renderMode 为 RenderMode.ScreenSpaceOverlay 时 传递参数 null

        // UI 坐标转换为屏幕坐标
        public static Vector2 UIPointToScreenPoint(Camera uiCamera, Vector3 worldPoint)
        {
            // RectTransform：target
            // worldPoint = target.position;

            Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(uiCamera, worldPoint);
            return screenPoint;
        }

        // 屏幕坐标转换为 UGUI 坐标
        public static Vector3 ScreenPointToUIPoint(Camera uiCamera, RectTransform rt, Vector2 screenPoint)
        {
            Vector3 globalMousePos;
            //UI屏幕坐标转换为世界坐标

            // 当 Canvas renderMode 为 RenderMode.ScreenSpaceCamera、RenderMode.WorldSpace 时 uiCamera 不能为空
            // 当 Canvas renderMode 为 RenderMode.ScreenSpaceOverlay 时 uiCamera 可以为空
            RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, screenPoint, uiCamera, out globalMousePos);
            // 转换后的 globalMousePos 使用下面方法赋值
            // target 为需要使用的 UI RectTransform
            // rt 可以是 target.GetComponent<RectTransform>(), 也可以是 target.parent.GetComponent<RectTransform>()
            // target.transform.position = globalMousePos;
            return globalMousePos;
        }

        // 屏幕坐标转换为 UGUI RectTransform 的 anchoredPosition
        public static Vector2 ScreenPointToUILocalPoint(Camera uiCamera, RectTransform parentRT, Vector2 screenPoint)
        {
            Vector2 localPos;

            RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRT, screenPoint, uiCamera, out localPos);
            // 转换后的 localPos 使用下面方法赋值
            // target 为需要使用的 UI RectTransform
            // parentRT 是 target.parent.GetComponent<RectTransform>()
            // 最后赋值 target.anchoredPosition = localPos;
            return localPos;
        }
    }
    
    public static class DebugHelper
    {
        public static void Info(this string self, params object[] debugInfo)
        {
            Debug.LogFormat(self, debugInfo);
        }

        public static void WarningInfo(this string self, params object[] debugInfo)
        {
            Debug.LogWarningFormat(self, debugInfo);
        }

        public static void ErrorInfo(this string self, params object[] debugInfo)
        {
            Debug.LogErrorFormat(self, debugInfo);
        }
    }
    
    public static class MathHelper
    {
        /// <summary>
        /// 将值从原始范围线性映射到目标范围
        /// </summary>
        /// <param name="value">要映射的值</param>
        /// <param name="fromMin">原始范围最小值</param>
        /// <param name="fromMax">原始范围最大值</param>
        /// <param name="toMin">目标范围最小值</param>
        /// <param name="toMax">目标范围最大值</param>
        /// <returns>映射后的值</returns>
        public static float Remap(float value, float fromMin, float fromMax, float toMin, float toMax)
        {
            // 计算原始范围内的比例 (0-1)
            float normalized = (value - fromMin) / (fromMax - fromMin);
        
            // 将比例应用到目标范围
            return Mathf.Lerp(toMin, toMax, normalized);
        }
    
        /// <summary>
        /// 带钳制功能的映射，确保结果在目标范围内
        /// </summary>
        public static float RemapClamped(float value, float fromMin, float fromMax, float toMin, float toMax)
        {
            float normalized = Mathf.Clamp01((value - fromMin) / (fromMax - fromMin));
            return Mathf.Lerp(toMin, toMax, normalized);
        }
    }

    public class TimeExtension
    {
        /// <summary>
        /// 获取以日期命名的名称
        /// 例 2023-09-04-10-23-01
        /// </summary>
        /// <returns>日期命名</returns>
        public static string GetDateName()
        {
            int hour = DateTime.Now.Hour;
            int minute = DateTime.Now.Minute;
            int second = DateTime.Now.Second;
            int year = DateTime.Now.Year;
            int month = DateTime.Now.Month;
            int day = DateTime.Now.Day;
            return string.Format("{0:D4}-{1:D2}-{2:D2}-{3:D2}-{4:D2}-{5:D2}", year, month, day, hour, minute, second);
        }

        /// <summary>
        /// 获得时间文本
        /// </summary>
        /// <param name="timeSpan"></param>
        /// <returns></returns>
        // public static string GetTimeString(TimeSpan timeSpan)
        // {
        //     if (timeSpan.Days > 0)
        //     {
        //         if (timeSpan.Hours > 0)
        //         {
        //             return Localization.mInstance.GetText("{0}天{1}小时", timeSpan.Days, timeSpan.Hours);
        //         }
        //         else
        //         {
        //             return Localization.mInstance.GetText("{0}天", timeSpan.Days);
        //         }
        //     }
        //     else if (timeSpan.Hours > 0)
        //     {
        //         if (timeSpan.Minutes > 0)
        //         {
        //             return Localization.mInstance.GetText("{0}小时{1}分", timeSpan.Hours, timeSpan.Minutes);
        //         }
        //         else
        //         {
        //             return Localization.mInstance.GetText("{0}小时", timeSpan.Hours);
        //         }
        //     }
        //     else if (timeSpan.Minutes > 0)
        //     {
        //         if (timeSpan.Seconds > 0)
        //         {
        //             return Localization.mInstance.GetText("{0}分{1}秒", timeSpan.Minutes, timeSpan.Seconds);
        //         }
        //         else
        //         {
        //             return Localization.mInstance.GetText("{0}分", timeSpan.Minutes);
        //         }
        //     }
        //     else
        //     {
        //         return Localization.mInstance.GetText("{0}秒", timeSpan.Seconds);
        //     }
        // }
        public class ListHelper
        {
            /// <summary>
            /// 按指定数量均分
            /// </summary>
            /// <returns></returns>
            private static List<List<T>> SpiltList<T>(List<T> Lists, int num)
            {
                List<List<T>> fz = new List<List<T>>();
                //元素数量大于等于 分组数量
                if (Lists.Count >= num)
                {
                    int avg = Lists.Count / num; //每组数量
                    int vga = Lists.Count % num; //余数
                    for (int i = 0; i < num; i++)
                    {
                        List<T> cList = new List<T>();
                        if (i + 1 == num)
                        {
                            cList = Lists.Skip(avg * i).ToList<T>();
                        }
                        else
                        {
                            cList = Lists.Skip(avg * i).Take(avg).ToList<T>();
                        }

                        fz.Add(cList);
                    }
                }
                else
                {
                    //最后一组 数量<=num
                    fz.Add(Lists); //元素数量小于分组数量
                }

                return fz;
            }
        }


        public class GameHelper
        {
            public static string ConvertToTimeString(int d)
            {
                int h = d / 3600;
                int m = (d - h * 3600) / 60;
                int s = d % 60;
                string str_m = m > 0 ? $"{m}分" : string.Empty;
                string str_s = d > 60 ? string.Empty : (s < 5 ? $"{5}秒" : $"{(int)(s / 10 + 1) * 10}秒");
                return (h > 0 ? $"{h}时" : string.Empty) + str_m + str_s;
            }


            /// <summary>
            /// 将数据转化为游戏数据
            /// </summary>
            /// <param name="d"></param>
            /// <returns></returns>
            public static string ConvertToGameString(double d)
            {
                string[] strings =
                {
                    "K", "M", "B", "T", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM",
                    "AN",
                    "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ"
                };
                int index = -1;
                while (d > 1000)
                {
                    index++;
                    d /= 1000;
                }

                if (index >= 0)
                {
                    if (index >= strings.Length)
                    {
                        return $"Nan";
                    }
                    else
                    {
                        return $"{d.ToString("0.##")}{strings[index]}";
                    }
                }
                else
                {
                    return d.ToString();
                }
            }
        }
    }

    /// <summary>
    /// 验证加密程序
    /// </summary>
    public class CheckPermission
    {
        public CheckPermission()
        {
            // 创建一个进程
            Process process = new Process();

            Debug.Log(Application.streamingAssetsPath + "/encryption-client-win.exe");

            // 设置进程启动信息
            process.StartInfo.FileName =
                Application.streamingAssetsPath + "/encryption-client-win.exe"; // 这里是 .exe 文件的路径
            process.StartInfo.Arguments = ""; // 如果有命令行参数，可以在这里设置
            process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
            process.StartInfo.RedirectStandardError = true; // 重定向标准错误
            process.StartInfo.UseShellExecute = false; // 不使用系统外壳启动
            process.StartInfo.CreateNoWindow = true; // 不创建窗口

            // 启动进程
            process.Start();

            // 获取标准输出和错误输出
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            // 等待进程完成
            process.WaitForExit();


            // 获取进程的退出代码
            int exitCode = process.ExitCode;

            // 打印输出和退出代码
            Debug.Log("Output: " + output);
            Debug.Log("Error: " + error);
            Debug.Log("Exit Code: " + exitCode);

            string keyContent = AES.AesDecrypt(output, "U2FsdGVkX19P6I00XYTyphusl4bzFQQO");
            Debug.Log(keyContent);

            if (keyContent.Trim().Substring(0, 5) == "false")
            {
                Application.Quit();
            }
            else if (keyContent.Trim().Substring(0, 4) == "true")
            {
                long time1 = int.Parse(keyContent.Trim().Substring(5));
                DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                TimeSpan timeSpan = DateTime.UtcNow - epochStart;
                long time2 = (long)timeSpan.TotalSeconds;
                Debug.Log(time2);
                if (Math.Abs(time1 - time2) > 10)
                {
                    Application.Quit();
                }
            }
        }
    }

    /// <summary>
    /// AES 加密
    /// 高级加密标准，是下一代的加密算法标准，速度快，安全级别高，
    /// 目前 AES 标准的一个实现是 Rijndael 算法
    /// </summary>
    public class AES
    {
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            try
            {
                Byte[] toEncryptArray = Convert.FromBase64String(str);

                RijndaelManaged rm = new RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };

                ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return null;
            }
        }
    }
}